<!--name: 'ThermalMap',-->
<template>
  <div>
    <div class="container">
      <div class="block">
        <div class="demonstration">选择年份及月份</div>
        <div class="picker">
          <el-date-picker
            v-model="info.standardTime"
            type="month"
            placeholder="选择月"
            @change="clickDate"
          ></el-date-picker>
        </div>
      </div>
    </div>
    <div class="container">
      <div class="block">
        <!--      <div class="demonstration">选择年份及月份</div>-->
        <!--      暂时设为normalTime，将value数据规范化后可统一-->
        <el-slider
          v-model="info.normalTime"
          :step="1"
          :max="700"
          :format-tooltip="formatTooltip"
          @change="clicked"
        ></el-slider>
      </div>
    </div>
    <!--  echarts-->
    <div class="echarts-box">
      <div class="chart-item">
        <div id="heatMapSst" ref="heatMapSst"></div>
      </div>
      <div class="chart-item">
        <div id="heatMapT300" ref="heatMapT300"></div>
      </div>
    </div>
    <div id="myEcharts" style="width: 80%; height: 70vh; margin: auto"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { ref, onMounted, onUnmounted, reactive } from "vue";
import chinaJson from "../assets/china.json";
import "echarts-gl";
import "echarts/map/js/world.js";
import geoJson from "echarts/map/json/world.json";
import "echarts-extension-amap";
// import jsonp from 'jsonp'
import { nino } from "../api";

export default {
  name: "ThermalMap",
  props: {
    width: String,
    height: String,
    data: {
      type: Array,
      required: true
    }
  },
  setup() {
    let myEcharts = echarts;
    const chartRef = ref(null);
    let chartSst = null;
    let chartLine = null;
    let chartT300 = null;
    let inputTime = "1985-11";
    let ninoData = nino.getNinoData({ time: inputTime });
    const info = reactive({
      chart: null,
      ninoMap: [],
      time: "1985-11", //获取到的时间
      standardTime: "2023-1",
      normalTime: ""
    });

    onMounted(() => {
      initLineChart();
      initHeatMap();
    });
    onUnmounted(() => {
      chartSst.dispose();
      chartLine.dispose();
      chartT300.dispose();
    });

    async function getNinoData(data) {
      let time = data ? data : "1985-11";
      ninoData = await nino.getNinoData({ time: time });
      let ninoMap = ninoData.data[0].map;
      console.log("data:", ninoMap);
      return ninoMap;
    }

    async function getNinoLine(data) {
      let time = data ? data : "1985-11";
      ninoData = await nino.getNinoData({ time: time });
      console.log("data", ninoData);
      let ninoLine = ninoData.data[0].preds;
      console.log("data:", ninoLine);
      return ninoLine;
    }

    async function initHeatMap() {
      ninoData = await getNinoData(info.time);
      // console.log('ninoData', ninoData)
      chartSst = myEcharts.init(
        document.getElementById("heatMapSst"),
        "purple-passion"
      );
      // 注册可用的地图
      myEcharts.registerMap("world", geoJson);
      // 设置echarts的option
      chartSst.setOption({
        title: {
          text: "SST",
          // subtext: "Sub Title",
          left: "center",
          top: "top",
          textStyle: {
            fontSize: 30
          },
          subtextStyle: {
            fontSize: 20
          }
        },
        visualMap: {
          min: -1,
          max: 2,
          calculable: true,
          orient: "horizontal",
          left: "center",
          bottom: "3%",
          inRange: {
            color: ["blue", "blue", "yellow", "red", "red"]
          },
          textStyle: {
            color: "#fff"
          }
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        geo: {
          map: "world",
          roam: false,
          itemStyle: {
            areaColor: "#323c48",
            borderColor: "#111"
          },
          emphasis: {
            label: {
              show: false
            }
          }
        },
        series: [
          {
            type: "heatmap",
            coordinateSystem: "geo",
            data: ninoData.map(({ lat, lon, sst, t300 }) => ({
              value: [lon - 180, lat - 45, sst]
            })),
            pointSize: 9,
            blurSize: 10
          }
        ]
      });
      window.onresize = function() {
        chartSst.resize();
      };

      chartT300 = myEcharts.init(
        document.getElementById("heatMapT300"),
        "purple-passion"
      );
      // 注册可用的地图
      myEcharts.registerMap("world", geoJson);
      // 设置echarts的option
      chartT300.setOption({
        title: {
          text: "T300",
          // subtext: "Sub Title",
          left: "center",
          top: "top",
          textStyle: {
            fontSize: 30
          },
          subtextStyle: {
            fontSize: 20
          }
        },
        visualMap: {
          min: -1,
          max: 2,
          calculable: true,
          orient: "horizontal",
          left: "center",
          bottom: "3%",
          inRange: {
            color: ["blue", "blue", "yellow", "red", "red"]
          },
          textStyle: {
            color: "#ffffff"
          }
        },
        geo: {
          map: "world",
          roam: false,
          itemStyle: {
            areaColor: "#323c48",
            borderColor: "#111"
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true
          },
          emphasis: {
            label: {
              show: false
            }
          }
        },
        series: [
          {
            type: "heatmap",
            coordinateSystem: "geo",
            data: ninoData.map(({ lat, lon, sst, t300 }) => ({
              value: [lon - 180, lat - 45, t300]
            })),
            pointSize: 9,
            blurSize: 10
          }
        ]
      });
      window.onresize = function() {
        chartT300.resize();
      };
    }

    async function initLineChart() {
      let lineData = await getNinoLine(info.time);
      console.log("lineData", lineData);
      let data = lineData;
      let x = data.map(item => {
        return item.lev;
      });
      let y_true = data.map(item => {
        return item.Ytrue;
      });
      let y_preds = data.map(item => {
        return item.preds;
      });
      chartLine = myEcharts.init(
        document.getElementById("myEcharts"),
        "purple-passion"
      );
      chartLine.setOption({
        title: {
          text: "厄尔尼诺现象预测"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: ["预测值", "实际值"]
        },
        grid: {
          left: "17%",
          right: "20%",
          bottom: "3%",
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: "category",
          // boundaryGap: false,
          name: "预测前置时间/月",
          data: x
        },
        yAxis: {
          type: "value",
          name: "ONI"
        },
        series: [
          {
            name: "预测值",
            type: "line",
            stack: "Total",
            data: y_preds
          },
          {
            name: "实际值",
            type: "line",
            stack: "Total",
            data: y_true
          }
        ]
      });
      window.onresize = function() {
        chartLine.resize();
      };
    }

    function clicked() {
      let date = formatTooltip(info.normalTime);
      info.time = date;
      let [year, month] = date.split("-");
      info.standardTime = new Date(parseInt(year), parseInt(month) - 1);
      console.log(info.standardTime);

      // inputTime = info.time
      initLineChart();
      initHeatMap();
    }

    async function clickDate() {
      console.log(info.standardTime);
      let year = info.standardTime.getFullYear();
      // let month = info.standardTime.getMonth() + 1 < 10 ? '0' + (info.standardTime.getMonth() + 1) : info.standardTime.getMonth() + 1
      let month = info.standardTime.getMonth() + 1;
      info.time = year + "-" + month;
      console.log("date:", info.time, info.standardTime);
      info.normalTime = parseInt(month) + (year - 1970) * 12 - 1;

      await initLineChart();
      await initHeatMap();
      // inputTime = info.time
    }

    function formatTooltip(val) {
      console.log(val);
      let year = 1970 + parseInt(val / 12);
      let month = 1 + parseInt(val % 12);
      console.log(year + "-" + month);
      /*      if (month < 10) {
              month = '0' + month.toString()
            } else {
              month = month.toString()
            }*/
      let date = year + "-" + month;
      console.log(date);
      return date;
    }

    /*    const pickerOptions = {
          disabledDate(time) {
            return time.getFullYear()<2018
          }
        }*/

    return {
      // initChart,
      chartRef,
      clicked,
      clickDate,
      formatTooltip,
      info
      // pickerOptions
      // standardTime,
      // normalTime
    };
  }

  /*    data() {
        return {
          chart: null,
          standardTime: '',
          normalTime: '',
          ninoMap: [],
          time: '1985-11'//获取到的时间
        };
      },*/
  /*  methods: {
      clicked() {
        console.log('this.inputTime',this)
        let date = this.formatTooltip(this.normalTime)
        this.time = date
        let [year, month] = date.split('-')
        this.standardTime = new Date(parseInt(year), parseInt(month) - 1)
        console.log(this.standardTime)
      },
      clickDate() {
        let year = this.standardTime.getFullYear()
        let month = this.standardTime.getMonth() + 1 < 10 ? '0' + (this.standardTime.getMonth() + 1) : this.standardTime.getMonth() + 1
        this.time = year + '-' + month
        console.log('date:', this.time, this.standardTime)
        this.normalTime = parseInt(month) + (year - 1970) * 12 - 1
      },
      formatTooltip(val) {
        let year = 1970 + parseInt(val / 12)
        let month = 1 + parseInt(val % 12)
        console.log(year + "-" + month)
        if (month < 10) {
          month = '0' + month.toString()
        } else {
          month = month.toString()
        }
        let date = year + "-" + month
        console.log(date)
        return date
      },
    }*/
};
</script>

<style scoped lang="scss">
.container {
  display: flex;
  justify-content: center;
}

@media screen and (min-width: 700px) {
  .echarts-box {
    display: flex;
    width: 100%;
    justify-content: center;
    margin-bottom: 10vh;
    .chart-item {
      width: 50%;
      height: 50vh;
    }
  }
  #heatMapSst {
    width: 100%;
    height: 50vh;
  }
  #heatMapT300 {
    width: 100%;
    height: 50vh;
  }
}
@media screen and (max-width: 699px) {
  .echarts-box {
    width: 100%;
    margin-bottom: 10vh;
    .chart-item {
      width: 100%;
      height: 50vh;
    }
  }
  #heatMapSst {
    width: 100%;
    height: 45vh;
  }
  #heatMapT300 {
    width: 100%;
    height: 45vh;
  }
}

.block {
  width: 60%;
  display: block;

  .demonstration {
    font-size: medium;
    font-weight: bold;
  }

  .picker {
    padding: 20px;
  }
}
</style>
